#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <vector>
#include "Mutex.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace MuteModule;
using namespace LogModule;
class Route
{
private:
    bool Exit(Inet_Addr& t)
    {
        for(auto& route : _route)
        {
            if(route == t)
            {
                return true;
            }
        }
        return false;
    }
    void Add(Inet_Addr& t)
    {
        LOG(LogLevel::DEBUG) << t.StringAddr() << " " << "上线";
        _route.push_back(t);
    }
    void Quit(Inet_Addr& t)
    {
        for(auto i = _route.begin(); i != _route.end(); i++)
        {
            if(t == *i)
            {
                LOG(LogLevel::DEBUG) << t.IP() << " " << "离线";
                _route.erase(i);
                break;
            }
        }
    }
public:
    Route()
    {

    }
    void Message(int fd, const std::string& message, Inet_Addr& t)
    {
        if(!Exit(t))
        {
            Add(t);
            
        }
        std::string tmp = t.StringAddr() + "# " + message;
        // for(auto& route : _route)
        // {
        //     //std::string tmp = t.IP() + "# " + message;  #我写的
        //     int n = sendto(fd, tmp.c_str(), tmp.size(), 0, (const struct sockaddr *)&route.Sockaddr_In(), sizeof(route.Sockaddr_In()));
        // }
            int n = sendto(fd, tmp.c_str(), tmp.size(), 0, (const struct sockaddr *)&t.Sockaddr_In(), sizeof(t.Sockaddr_In()));
        if(message == "Quit")
        {
            
            Quit(t);
        }
    }
    ~Route()
    {

    }
private:
    std::vector<Inet_Addr> _route;
};